<?php

$user = new User;

if ($_POST) {
	if (!isset($_POST['core']['username'])) $_POST['core']['username'] = $_POST['core']['email'];
	if (!isset($user->user['custom']) or !is_array($user->user['custom'])) $user->user['custom'] = array();
	if (!isset($_POST['custom']) or !is_array($_POST['custom'])) $_POST['custom'] = array();
	
	if (!isset($_POST['core']['username'])) $_POST['core']['username'] = $_POST['core']['email'];
	
	$user->user['core'] = array_merge($user->user['core'], $_POST['core']);
	
	// remove any custom values that either don't have meta data or are set private
	foreach($_POST['custom'] as $key => $val) {
		foreach($user->users_custom_schema as $field) {
			if ($key == $field['Field']) {
				if (!isset($field['meta']) or $field['meta']['private']) {
					unset($_POST['custom'][$key]);
					continue;
				}
			}
		}
	}
	
	$user->user['custom'] = array_merge($user->user['custom'], $_POST['custom']);
	$user->user['password1'] = $_POST['password1'];
	$user->user['password2'] = $_POST['password2'];

	if ($user->save($errors)) {
		// all ok
		$smarty->assign('success', true);
		$mailer = new Webtaculous_Mail_Auto('user_register');
		$mailer->to($user->user['core']['email']);
		$mailer->to_name("{$user->user['core']['first_name']} {$user->user['core']['last_name']}");
		$mailer->value('username', $user->user['core']['username']);
		$mailer->value('email', $user->user['core']['email']);
		$mailer->value('title', $user->user['core']['title']);
		$mailer->value('first_name', $user->user['core']['first_name']);
		$mailer->value('last_name', $user->user['core']['last_name']);
		$mailer->value('custom', $user->user['custom']);
		$mailer->send();
	} else {
		$smarty->assign('errors', $errors);
	}
	
}

$smarty->assign('user', $user->user);
$smarty->assign('users_custom_schema', $user->users_custom_schema);

$smarty->display('user/register.tpl.html');